package com.zero.yygh.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zero.yygh.common.exception.CommonException;
import com.zero.yygh.common.helper.JwtHelper;
import com.zero.yygh.common.result.ResultCodeEnum;
import com.zero.yygh.enums.AuthStatusEnum;
import com.zero.yygh.model.user.Patient;
import com.zero.yygh.model.user.UserInfo;
import com.zero.yygh.model.user.UserLoginRecord;
import com.zero.yygh.user.mapper.UserInfoMapper;
import com.zero.yygh.user.service.PatientService;
import com.zero.yygh.user.service.UserInfoService;
import com.zero.yygh.vo.user.LoginVo;
import com.zero.yygh.vo.user.UserAuthVo;
import com.zero.yygh.vo.user.UserInfoQueryVo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zero
 * @desc
 * @create 2021/4/2
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private PatientService patientService;


    /**
     * 会员登录
     * @param loginVo 用户信息
     * @author zero
     * @date 2021/4/2 14:02
     */
    @Override
    public Map<String, Object> login (LoginVo loginVo) {
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        //校验参数
        if(StringUtils.isEmpty(phone) ||
                StringUtils.isEmpty(code)) {
            throw new CommonException(ResultCodeEnum.PARAM_ERROR);
        }

        // 校验校验验证码
        String mobileCode = redisTemplate.opsForValue().get(phone);
        if (!code.equals(mobileCode)) {
            throw new CommonException(ResultCodeEnum.CODE_ERROR);
        }

        // 绑定手机
        UserInfo userInfo = null;
        if(!StringUtils.isEmpty(loginVo.getOpenid())) {
            userInfo = this.getByOpenId(loginVo.getOpenid());
            if (null != userInfo) {
                userInfo.setPhone(loginVo.getPhone());
                this.updateById(userInfo);
            }else {
                throw new CommonException(ResultCodeEnum.DATA_ERROR);
            }
        }

        //手机号登录
        if(null == userInfo) {
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone", phone);
            //获取会员
            userInfo = baseMapper.selectOne(queryWrapper);
            // 否则，直接注册会员
            if(null == userInfo) {
                userInfo = new UserInfo();
                userInfo.setName("");
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                this.save(userInfo);
            }
        }

        //校验是否被禁用
        if(userInfo.getStatus() == 0) {
            throw new CommonException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }

        //记录登录
        UserLoginRecord userLoginRecord = new UserLoginRecord();
        userLoginRecord.setUserId(userInfo.getId());
        userLoginRecord.setIp(loginVo.getIp());
        // TODO 保存登录记录


        //返回页面显示名称
        Map<String, Object> map = new HashMap<>(2);
        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);
        // 生成token
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token", token);
        return map;
    }

    /**
     * 根据openId插叙用户信息
     * @param openId openid
     * @return com.zero.yygh.model.user.UserInfo
     * @author zero
     * @date 2021/4/12 11:24
     */
    @Override
    public UserInfo getByOpenId (String openId) {
        return baseMapper.selectOne(new QueryWrapper<UserInfo>().eq("openid", openId));
    }

    /**
     * 用户认证
     * @param userId     用户id
     * @param userAuthVo 认证信息
     * @author zero
     * @date 2021/4/12 15:09
     */
    @Override
    public void userAuth (Long userId, UserAuthVo userAuthVo) {
        // 根据用户id查询用户信息
        UserInfo userInfo = baseMapper.selectById(userId);
        userInfo.setName(userAuthVo.getName());
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        // 更新信息
        baseMapper.updateById(userInfo);
    }

    /**
     * 查询用户列表，分页条件查询
     * @param pageParam       分页参数
     * @param userInfoQueryVo 查询参数
     * @return com.baomidou.mybatisplus.core.metadata.IPage<com.zero.yygh.model.user.UserInfo>
     * @author zero
     * @date 2021/4/18 19:53
     */
    @Override
    public IPage<UserInfo> selectPage (Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {
        //UserInfoQueryVo获取条件值
        //用户名称
        String name = userInfoQueryVo.getKeyword();
        //用户状态
        Integer status = userInfoQueryVo.getStatus();
        //认证状态
        Integer authStatus = userInfoQueryVo.getAuthStatus();
        //开始时间
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();
        //结束时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();
        //对条件值进行非空判断
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(name)) {
            wrapper.like("name",name);
        }
        if(!StringUtils.isEmpty(status)) {
            wrapper.eq("status",status);
        }
        if(!StringUtils.isEmpty(authStatus)) {
            wrapper.eq("auth_status",authStatus);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time",createTimeEnd);
        }
        //调用mapper的方法
        IPage<UserInfo> pages = baseMapper.selectPage(pageParam, wrapper);
        //编号变成对应值封装
        pages.getRecords().forEach(this::packageUserInfo);
        return pages;
    }

    /**
     * 锁定用户
     * @param userId 用户id
     * @param status 状态
     * @author zero
     * @date 2021/4/20 10:57
     */
    @Override
    public void lock (Long userId, Integer status) {
        if(status == 0 || status == 1) {
            UserInfo userInfo = this.getById(userId);
            userInfo.setStatus(status);
            this.updateById(userInfo);
        }
    }

    /**
     * 查询用户详情
     * @param userId 用户id
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author zero
     * @date 2021/4/20 11:04
     */
    @Override
    public Map<String, Object> show (Long userId) {
        Map<String,Object> map = new HashMap<>(2);
        //根据userid查询用户信息
        UserInfo userInfo = this.packageUserInfo(baseMapper.selectById(userId));
        map.put("userInfo",userInfo);
        //根据userid查询就诊人信息
        List<Patient> patientList = patientService.findAllUserId(userId);
        map.put("patientList",patientList);
        return map;

    }

    /**
     * 用户认证审批
     * @param userId     用户id
     * @param authStatus 认证状态
     * @author zero
     * @date 2021/4/20 12:57
     */
    @Override
    public void approval (Long userId, Integer authStatus) {
        if(authStatus == 2 || authStatus == -1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }
    }

    /**
     * 编号变成对应值封装
     * @author zero
     * @date 2021/4/18 19:56
     * @param userInfo 用户信息
     * @return com.zero.yygh.model.user.UserInfo
     */
    private UserInfo packageUserInfo(UserInfo userInfo) {
        //处理认证状态编码
        userInfo.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //处理用户状态 0  1
        String statusString = userInfo.getStatus() == 0 ? "锁定" : "正常";
        userInfo.getParam().put("statusString",statusString);
        return userInfo;
    }
}
